package com.lzx.iteam;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.lzx.iteam.base.FindViewById;
import com.lzx.iteam.base.MyBaseActivity;
import com.lzx.iteam.bean.AddressData;
import com.lzx.iteam.net.AsynHttpClient;
import com.lzx.iteam.net.GetMsgHttpReceiver;
import com.lzx.iteam.net.GetQnTokenMsg;
import com.lzx.iteam.net.LocalLogin;
import com.lzx.iteam.selectimage.Bimp;
import com.lzx.iteam.util.*;
import io.rong.imageloader.core.ImageLoader;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * **********************************
 * User: zhangshuai
 * Date: 2016年 09月 02日
 * Time: 上午10:24
 *
 * @QQ : 1234567890
 * **********************************
 */
public class LegworkSignActivity extends MyBaseActivity implements View.OnClickListener {

    @FindViewById(id = R.id.title_ll_back)
    private LinearLayout mLayoutBack;
    @FindViewById(id = R.id.title_tv_right)
    private TextView mTvRight;
    @FindViewById(id = R.id.title_tv_center)
    private TextView mTvTitle;
    @FindViewById(id = R.id.legwork_gallery_layout)
    private LinearLayout mImageHLinearLayout;
    @FindViewById(id = R.id.legwork_rl_address)
    private RelativeLayout mAddressLayout;
    @FindViewById(id = R.id.legwork_tv_address)
    private TextView mTvAddress;
    @FindViewById(id = R.id.legwork_tv_sign)
    private TextView mTvSign;
    @FindViewById(id = R.id.legwork_tv_time)
    private TextView mTvTime;
    @FindViewById(id = R.id.legwork_et_sign)
    private EditText mEtRemark;

    public int index;
    private String mGroupId, mFormId;
    private String mFilePath;
    private String mRemark;
    private JSONArray mAttachment;
    private Bitmap mBitMap;
    private List<Map<String, byte[]>> keyByte = new ArrayList<Map<String, byte[]>>();

    private LocationUtil mLocationUtil;
    private double mLatitude, mLongitude;

    private Dialog mWaitDialog;
    private AddressData mAddressData;

    private final int LEGWORK_DO = 10000;
    private final int GET_QN_TOKEN = 10001;
    public final int LEGWORK_ADDRESS_CHOOSE = 2001;
    private String Tag = "LegworkSignActivity";


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            httpReqDlgDismiss();
            if (msg.arg1 != 0) {
                Toast.makeText(mActivity, (String) msg.obj,
                      Toast.LENGTH_LONG).show();
            } else {
                switch (msg.what) {
                    case GET_QN_TOKEN:
                        Map<String, Object> map = (HashMap<String, Object>) msg.obj;
                        for (int i = 0; i < keyByte.size(); i++) {
                            Map<String, byte[]> map1 = keyByte.get(i);
                            for (String key : map1.keySet()) {
                                setPhoto((String) map.get(key), map1.get(key), key);
                            }

                        }
                        break;
                    case LEGWORK_DO:
                        if (Bimp.mPictureData.size() > 0) {
                            Bimp.mPictureData.clear();
                        }
                        for (String data : Bimp.tempSelectBitmap) {
                            Bimp.mPictureData.add(data);
                            Log.d("talk_list_send_da", data);
                        }
                        Bimp.tempSelectBitmap.clear();
                        try {
                            JSONObject jsonObject = ((JSONObject) msg.obj).getJSONObject(AsynHttpClient.KEY_CC_DATA);
                            Constants.NEW_LEGWORK_ID = jsonObject.getString("_id");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                       /* Toast.makeText(mActivity, "创建成功",
                              Toast.LENGTH_LONG).show();*/
                        finish();
                        break;
                }
            }
        }
    };

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.legwork_sign_layout);
    }

    @Override
    public void initListener() {
        mLayoutBack.setOnClickListener(this);
        mTvSign.setOnClickListener(this);
        mAddressLayout.setOnClickListener(this);
    }

    @Override
    public void initData() {
        mTvTitle.setText("签到");
        Intent intent = getIntent();
        mGroupId = intent.getStringExtra("group_id");
        mFormId = intent.getStringExtra("form_id");
        mAddressData = (AddressData) intent.getSerializableExtra("addressData");
        long time = System.currentTimeMillis();
        mTvTime.setText(DateUtil.getYearDate(time));
        mTvAddress.setText(mAddressData.getAddress());

    }

    @Override
    protected void onResume() {
        super.onResume();
        setImageMsg();
    }

    private void setImageMsg() {
        int imgSize = 0;
        if (Bimp.tempSelectBitmap != null) {
            imgSize = Bimp.tempSelectBitmap.size();
            mImageHLinearLayout.removeAllViews();
            if (imgSize > 0) {
                for (int i = 0; i < imgSize; i++) {
                    final String image = Bimp.tempSelectBitmap.get(i);
                    final int position = i;
                    final View view = LayoutInflater.from(mActivity).inflate(R.layout.ho_list_item, mImageHLinearLayout, false);
                    ImageView mIvDelete = (ImageView) view.findViewById(R.id.event_iv_item_delete);
                    ImageView mIvImage = (ImageView) view.findViewById(R.id.event_iv_item_image);
                    ImageLoader.getInstance().displayImage("file://" + image, mIvImage, ImageLoaderInterface.optionEventImage);

                    mIvDelete.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bimp.deletePhoto(image);
                            Bimp.tempSelectBitmap.remove(image);
                            setImageMsg();
                        }
                    });
                    mIvImage.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent(mActivity, ImagePagerActivity.class);
                            intent.putExtra(Constants.IMAGE_ORIGIN, Constants.IMAGE_ORIGIN_LOCAL_ARRAY);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, Bimp.tempSelectBitmap);
                            intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
                            startActivity(intent);
                        }
                    });
                    mImageHLinearLayout.addView(view);
                }

            }
            if (imgSize < 3) {
                ImageView photo = new ImageView(mActivity);
                photo.setImageDrawable(getResources().getDrawable(R.drawable.legwork_photo_selector));
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                      LinearLayout.LayoutParams.MATCH_PARENT);
                photo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mFilePath = PhotoUtil.doTakePhotoEvent(mActivity);
                    }
                });
                params.gravity = Gravity.CENTER;
                if (imgSize != 0) {
                    params.leftMargin = 20;
                }
                photo.setLayoutParams(params);
                mImageHLinearLayout.addView(photo);
            }

        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_ll_back:
                Bimp.deleteAllPhoto();
                finish();
                break;
            case R.id.legwork_tv_sign:
                refreshLoction();
                break;
            case R.id.legwork_rl_address:
                Intent address = new Intent(LegworkSignActivity.this, LegworkMainActivity.class);
                address.putExtra("group_id", mGroupId);
                address.putExtra("form_id", mFormId);
                address.setAction("update");
                startActivityForResult(address, LEGWORK_ADDRESS_CHOOSE);
                break;

        }
    }

    //设置图片
    public void setPhoto(String token, byte[] file, String fileName) {
        if (token != null) {
            Log.d("七牛--token", token);
            Log.d("七牛--fileName", fileName);
            DialerApp.getUploadManager(this).put(file, fileName, token,
                  new UpCompletionHandler() {
                      @Override
                      public void complete(String key, ResponseInfo info, JSONObject response) {
                          Log.d("七牛--info.isOk()", info.isOK() + "--response" + response);
                          ++index;
                          if (mAttachment.length() == index) {
                              mHandler.postDelayed(new Runnable() {
                                  @Override
                                  public void run() {
                                      Bimp.deleteAllPhotoAfterSend();
                                      Constants.NEW_LEGWORK_ID = "";
                                  }
                              }, 2000);
                              Log.d("legwork_send_da", " 发送完成 ");
                          } else {
                              Log.d("legwork_send_da", " 发送还没有完成 ===== ");
                          }
                      }
                  }, null);
        }
    }


    /**
     * 获取 token
     *
     * @param keys
     */
    public void getQnToken(String keys) {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_KEY, keys));
        GetQnTokenMsg getQnTokenMsg = new GetQnTokenMsg(mHandler.obtainMessage(GET_QN_TOKEN));
        getQnTokenMsg.mApi = AsynHttpClient.API_QN_GET_EVENT_TOKEN;
        getQnTokenMsg.mParams = mList;
        AsynHttpClient.getInstance(this).execUserHttp(getQnTokenMsg);
    }

    /**
     * 签到
     */
    private void legworkDo() {
        List<NameValuePair> mList = new ArrayList<NameValuePair>();
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_SID, LocalLogin.getInstance().mSid));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_GROUP_ID, mGroupId));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_FORM_ID, mFormId));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_REMARK, mRemark));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_ADDRESS, mAddressData.getAddress()));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_LATITUDE, mAddressData.getLatitude() + ""));
        mList.add(new BasicNameValuePair(AsynHttpClient.KEY_LONGITUDE, mAddressData.getLongitude() + ""));
        if (mAttachment != null && mAttachment.length() > 0) {
            mList.add(new BasicNameValuePair(AsynHttpClient.KEY_EVENT_ATTACHMENT, mAttachment.toString()));
        }

        GetMsgHttpReceiver msg = new GetMsgHttpReceiver(mHandler.obtainMessage(LEGWORK_DO));
        msg.mApi = AsynHttpClient.API_EVENT_LEGWORK_DO;
        msg.mParams = mList;
        AsynHttpClient.getInstance(this).execEventHttp(msg);


    }

    /**
     * 显示等待的dialog
     */
    private void httpReqDlgShow() {
        if (mWaitDialog == null) {
            mWaitDialog = AllDialogUtil.getInstance(mActivity).waitDialog();
//            mProgressDialog.setCancelable(false);
            mWaitDialog.show();
        }

    }

    /**
     * 取消等待的dialog
     */
    private void httpReqDlgDismiss() {
        if (mWaitDialog != null && mWaitDialog.isShowing()) {
            mWaitDialog.dismiss();
            mWaitDialog = null;
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO 红米手机拍照 有时页面会被销毁 此时需要保存拍照地址
        outState.putString("pic_path", mFilePath);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO 取出保存的拍照地址
        mFilePath = savedInstanceState.getString("pic_path");
        super.onRestoreInstanceState(savedInstanceState);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PhotoUtil.CAMERA_WITH_DATAA:
                if (Bimp.tempSelectBitmap.size() < 3 && resultCode == RESULT_OK) {
                    Bitmap bitmap = PhotoUtil.readBitmapFromPath(this, mFilePath, false);
                    int degree = PhotoUtil.getExifOrientation(mFilePath);
                    if (degree != 0) {
                        bitmap = PhotoUtil.rotaingImageView(bitmap, degree);
                        FileUtils.deleteFolderFile(mFilePath, true);
                        mFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Yun/Images/" + PhotoUtil.saveBitmaptoSdCard(bitmap, "/Yun/Images");
                    }
                    Bimp.tempSelectBitmap.add(mFilePath);
                    setImageMsg();
                }
                break;
            case LEGWORK_ADDRESS_CHOOSE:
                if (resultCode == RESULT_OK) {
                    mAddressData = (AddressData) data.getSerializableExtra("addressData");
                    long time = System.currentTimeMillis();
                    mTvTime.setText(DateUtil.getYearDate(time));
                    mTvAddress.setText(mAddressData.getAddress());
                }
                break;
        }
    }

    private void refreshLoction() {
        if (mLocationUtil != null) {
            mLocationUtil.stopLocation();
            mLocationUtil.destoryLocation();
            mLocationUtil = null;
        }
        httpReqDlgShow();
        mLocationUtil = new LocationUtil(this);
        mLocationUtil.setListener(new LocationUtil.LocationStatus() {
            @Override
            public void onLocated(BDLocation location) {
                Log.d("sign_loction", " loction ");
                // map view 销毁后不在处理新接收的位置
                if (location == null) {
                    return;
                }
                mLatitude = location.getLatitude();
                mLongitude = location.getLongitude();
                if (getDistance(mLatitude, mLongitude).length() > 3) {
                    httpReqDlgDismiss();
                    showNoticeDlg("对不起，当前所在位置与外勤打卡位置相差大于1000米，无法进行打卡");
                } else {
                    signLegworkDo();
                }
                mLocationUtil.stopLocation();
                mLocationUtil.destoryLocation();
                mLocationUtil = null;
            }
        });

    }

    private String getDistance(double latitude, double longitude) {
        LatLng start = new LatLng(latitude, longitude);
        LatLng end = new LatLng(mAddressData.getLatitude(), mAddressData.getLongitude());
        //  DecimalFormat df = new DecimalFormat("#.0");//保留1位小数
        //return df.format(DistanceUtil.getDistance(start, end) * 1000) + "";
        Log.i(Tag, "签到经纬度 latitude:" + mAddressData.getLatitude() + "---" + "longitude:" + mAddressData.getLongitude());
        Log.i(Tag, "定位经纬度 latitude:" + latitude + "---" + "longitude:" + longitude);
        Log.i(Tag, "距离 distance:" + DistanceUtil.getDistance(start, end));
        return String.valueOf(DistanceUtil.getDistance(start, end)).split("\\.")[0];
    }

    private void signLegworkDo() {
        mRemark = mEtRemark.getText().toString().trim();
        if (Bimp.tempSelectBitmap.size() > 0) {
            mAttachment = new JSONArray();
            StringBuilder stringBuilder = new StringBuilder();
            for (String image : Bimp.tempSelectBitmap) {
                Map<String, byte[]> token = new HashMap<String, byte[]>();
                String key = UUID.randomUUID().toString() + System.currentTimeMillis();
                if (mBitMap != null) {
                    if (!mBitMap.isRecycled()) {
                        mBitMap.recycle();
                    }
                    mBitMap = null;
                }
                mBitMap = PhotoUtil.readBitmapFromPath(mActivity, image, true);
                if (mBitMap != null && !mBitMap.isRecycled()) {
                    byte[] bytes = PhotoUtil.compressImage(mBitMap);
                    token.put(key, bytes);
                }
                stringBuilder.append(key + ",");
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", "1");
                    jsonObject.put("data", key);
                    mAttachment.put(jsonObject);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                keyByte.add(token);
            }
            getQnToken(stringBuilder.substring(0, stringBuilder.length() - 1));

        }
        legworkDo();
    }

    public void showNoticeDlg(String msg) {
        AllDialogUtil mDialogUtil = AllDialogUtil.getInstance(this);
        mDialogUtil.titleMsgBtnStyle("提示", msg, "知道了");

        mDialogUtil.setOnDialogListener(new AllDialogUtil.DialogOnClickListener() {
            @Override
            public void onConfirmClick(Dialog lDialog) {
                lDialog.dismiss();
                Bimp.deleteAllPhoto();
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onCancelClick(Dialog lDialog) {
                lDialog.dismiss();
            }
        });
    }

}
